package zoran.wang;

import org.junit.Test;
import zoran.wang.tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 力扣解题过程
 */
public class Solution {

    @Test
    public void test() {

        /*
        root = [3,9,20,15,7,null,null]

              3
          9       20
       15   7
         */
        TreeNode treeNode = new TreeNode(3);
        treeNode.left = new TreeNode(9);
        treeNode.right = new TreeNode(20);
        treeNode.left.left = new TreeNode(15);
        treeNode.left.right = new TreeNode(7);

        int i = minDepth(treeNode);
        System.out.println(i);

    }

    // 最短路径
    public int minDepth(TreeNode root) {

        if (root == null) return 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        // root 本身就是一层，depth 初始化为 1
        int depth = 1;

        while (!q.isEmpty()) {

            int sz = q.size();
            // 遍历当前层的节点
            for (int i = 0; i < sz; i++) {
                TreeNode cur = q.poll();

                // 判断是否到达叶子结点
                if (cur.left == null && cur.right == null)
                    return depth;

                // 将下一层节点加入队列
                if (cur.left != null)
                    q.offer(cur.left);
                if (cur.right != null)
                    q.offer(cur.right);
            }
            // 这里增加步数
            depth++;
        }
        return depth;
    }
}
